package com.iplatform.iplatformuser.function.resource.api.v1;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iplatform.iplatformuser.common.ConstantUtil;
import com.iplatform.iplatformuser.common.ResponseMsg;
import com.iplatform.commons.pagination.Pagination;
import com.iplatform.iplatformuser.function.resource.service.inter.IResurceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iplatform.module.privilege.mate.ResInfoBean;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Title: ApiResourceController Description:资源查询
 *
 * @author yb
 *
 */
@Api(tags = "资源查询")
@RestController
@RequestMapping("/api/v1/resources")
public class ApiResourcesController {
	@Autowired
	private IResurceService service;

	@Value("${spring.datasource.driver-class-name}")
	private String dataSource;

	@ApiOperation(value = "查看所有资源信息")
	@RequestMapping(value = "queryResourceList", method = RequestMethod.POST)
	public ResponseEntity<PageInfo<ResInfoBean>> queryResourceList(HttpServletRequest request,
                                                                   @RequestParam @ApiParam(hidden = true) Map<String, String> formMap,
                                                                   @ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination) {
		String type = formMap.get("type");
		List<ResInfoBean> resultList = new ArrayList<ResInfoBean>();
		if ("com.mysql.jdbc.Driver".equals(dataSource)) {
			if ("ORG".equals(type)) {
				List<ResInfoBean> bean = service.queryResByOrgForMySql(formMap);
				for (ResInfoBean R : bean) {
					ResInfoBean resInfoBean = new ResInfoBean();
					try {
						resInfoBean = (ResInfoBean) R.clone();
					} catch (CloneNotSupportedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					resInfoBean.setOrgChild(null);
					resInfoBean.setResName(space(resInfoBean.getResName(), resInfoBean.getLevel()));
					resultList.add(resInfoBean);
					getChildListOrg(resultList, R);
				}
			} else if ("SPEC".equals(type)) {
				List<ResInfoBean> bean = service.queryResBySpecForMySql(formMap);
				for(ResInfoBean R:bean) {
					ResInfoBean resInfoBean =new ResInfoBean();
					try {
						resInfoBean = (ResInfoBean) R.clone();
					} catch (CloneNotSupportedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					resInfoBean.setSpecChild(null);
					resInfoBean.setResName(space(resInfoBean.getResName(), resInfoBean.getLevel()));
					resultList.add(resInfoBean);
					getChildListSpec(resultList, R);
				}
			}else if ("MENU".equals(type)) {
				List<ResInfoBean> bean = service.queryResByMenuForMySql(formMap);
				for(ResInfoBean R: bean) {
					ResInfoBean res= new ResInfoBean();
					try {
						res = (ResInfoBean) R.clone();
					} catch (CloneNotSupportedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					res.setMenuChild(null);
					res.setResName(space(res.getResName(), res.getLevel()));
					resultList.add(res);
					getChildListMenu(resultList, R);
				}
			}else if ("M_ORG".equals(type)) {
				List<ResInfoBean> bean = service.queryResByManagerOrgForMySql(formMap);
				for (ResInfoBean R : bean) {
					ResInfoBean resInfoBean = new ResInfoBean();
					try {
						resInfoBean = (ResInfoBean) R.clone();
					} catch (CloneNotSupportedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					resInfoBean.setOrgChild(null);
					resInfoBean.setResName(space(resInfoBean.getResName(), resInfoBean.getLevel()));
					resultList.add(resInfoBean);
					getChildListOrg(resultList, R);
				}
			}else {
				PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
				resultList = service.queryResInfo(formMap);
				PageInfo<ResInfoBean> pageInfo = new PageInfo<>(resultList);
				return new ResponseEntity<>(pageInfo, HttpStatus.OK);
			}
			if(formMap.get("resName")!=null&&formMap.get("resName")!="") {
				List<ResInfoBean> list=new ArrayList<>();
				for (int i = 0; i < resultList.size(); i++) {
					if(resultList.get(i).getResName().contains(formMap.get("resName"))) {
						list.add(resultList.get(i));
					}
				}
				resultList.clear();
				resultList=list;
			}
			PageInfo<ResInfoBean> pageInfo = new PageInfo<>();
			pageInfo.setTotal(resultList.size());
			pageInfo.setPages(resultList.size()/pagination.getPageSize()+1);
			pageInfo.setPageNum(pagination.getPageNum());
			pageInfo.setPageSize(pagination.getPageSize());
			List<ResInfoBean> list=resultList.subList((pagination.getPageNum()-1)*pagination.getPageSize(),
					(pagination.getPageNum()-1)*pagination.getPageSize()+pagination.getPageSize()<resultList.size()?
							(pagination.getPageNum()-1)*pagination.getPageSize()+pagination.getPageSize():resultList.size());
			pageInfo.setList(list);
			return new ResponseEntity<>(pageInfo, HttpStatus.OK);
		}else {
			PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
			if ("ORG".equals(type)) {
				resultList = service.queryResByOrg(formMap);
			}else if ("SPEC".equals(type)) {
				resultList = service.queryResBySpec(formMap);
			}else if ("MENU".equals(type)) {
				resultList = service.queryResByMenu(formMap);
			}else if ("M_ORG".equals(type)) {
				resultList = service.queryResByManagerOrg(formMap);
			}else {
				resultList = service.queryResInfo(formMap);
			}
			PageInfo<ResInfoBean> pageInfo = new PageInfo<>(resultList);
			return new ResponseEntity<>(pageInfo, HttpStatus.OK);
		}
	}

	public void getChildListOrg(List<ResInfoBean> testList, ResInfoBean test) {
		List<ResInfoBean> child = test.getOrgChild();
		for (ResInfoBean chilTest : child) {
			ResInfoBean tmp = new ResInfoBean();
			try {
				tmp = (ResInfoBean) chilTest.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
			tmp.setOrgChild(null);
			tmp.setResName(space(tmp.getResName(), tmp.getLevel()));
			testList.add(tmp);
			getChildListOrg(testList, chilTest);
		}
	}

	public void getChildListSpec(List<ResInfoBean> testList, ResInfoBean test) {
		List<ResInfoBean> child = test.getSpecChild();
		for (ResInfoBean chilTest : child) {
			ResInfoBean tmp = new ResInfoBean();
			try {
				tmp = (ResInfoBean) chilTest.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
			tmp.setSpecChild(null);
			tmp.setResName(space(tmp.getResName(), tmp.getLevel()));
			testList.add(tmp);
			getChildListSpec(testList, chilTest);
		}
	}

	public void getChildListMenu(List<ResInfoBean> testList, ResInfoBean test) {
		List<ResInfoBean> child = test.getMenuChild();
		for (ResInfoBean chilTest : child) {
			ResInfoBean tmp = new ResInfoBean();
			try {
				tmp = (ResInfoBean) chilTest.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
			tmp.setMenuChild(null);
			tmp.setResName(space(tmp.getResName(), tmp.getLevel()));
			testList.add(tmp);
			getChildListMenu(testList, chilTest);
		}
	}

	private String space(String name, int level) {
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i < level; i++) {
			sb.append("        ");
		}
		System.out.println(sb.toString() + name);
		return sb.toString() + name;
	}

	@ApiOperation(value = "同步资源")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", paramType = "query", name = "type", value = "类型", required = false) })
	@RequestMapping(value = "selsyn", method = RequestMethod.POST)
	public ResponseEntity<ResponseMsg> selsyn(@RequestParam @ApiParam(hidden = true) Map<String, String> formMap) {
		String type = formMap.get("type");
		if ("SPEC".equals(type)) {
			service.insertOrUpdateResSpec(formMap);
		} else if ("ORG".equals(type)) {
			service.insertOrUpdateResOrg(formMap);
		} else if ("MENU".equals(type)) {
			service.insertOrUpdateResMenu(formMap);
		} else if ("TARGET".equals(type)) {
			service.insertOrUpdateResTarget(formMap);
		} else if ("M_ORG".equals(type)) {
			service.insertOrUpdateResManagerOrg(formMap);
		}
		return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
	}

	/**
	 * 查询资源代码和资源名称
	 *
	 * @param formMap
	 * @param pagination
	 * @return
	 */
	@ApiOperation(value = "查询资源代码和资源名称")
	@RequestMapping(value = "/codeAndNameList", method = RequestMethod.POST)
	public ResponseEntity<JSONObject> codeAndNameList() {
		List<Map<String, String>> resultList = service.queryResNameAndCode();

		JSONObject allObject = new JSONObject();
		JSONArray arrayCode = new JSONArray();
		JSONArray arrayName = new JSONArray();

		for (Map<String, String> data : resultList) {
			if (!StringUtils.isEmpty(data.get("code"))) {
				JSONObject objectCode = new JSONObject();
				objectCode.put("code", data.get("code"));
				arrayCode.add(objectCode);
			}

			if (!StringUtils.isEmpty(data.get("resName"))) {
				JSONObject objectName = new JSONObject();
				objectName.put("resName", data.get("resName"));
				arrayName.add(objectName);
			}
		}

		allObject.put("code", arrayCode);
		allObject.put("name", arrayName);

		return new ResponseEntity<>(allObject, HttpStatus.OK);
	}

	@ApiOperation(value = "根据资源实际ID和类型删除资源")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", paramType = "query", name = "resId", value = "资源实际ID", required = true),
			@ApiImplicitParam(dataType = "String", paramType = "query", name = "resType", value = "类型", required = true) })
	@RequestMapping(value = "/deleteByResIdAndType", method = RequestMethod.POST)
	public ResponseEntity<ResponseMsg> deleteByResIdAndType(
			@RequestParam @ApiParam(hidden = true) Map<String, String> formMap) {

		service.deleteByResIdAndType(formMap);

		return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
	}

	@ApiOperation(value = "根据菜单ID同步此菜单")
	@ApiImplicitParams({
			@ApiImplicitParam(dataType = "String", paramType = "query", name = "menuId", value = "菜单ID", required = true) })
	@RequestMapping(value = "/insertOrUpdateResMenuById", method = RequestMethod.POST)
	public ResponseEntity<ResponseMsg> insertOrUpdateResMenuById(
			@RequestParam @ApiParam(hidden = true) Map<String, String> formMap) {

		service.insertOrUpdateResMenuById(formMap);

		return new ResponseEntity<>(new ResponseMsg(ConstantUtil.SUCCESS), HttpStatus.OK);
	}

}
